package view_alertwebhook

import (
	"bigdevops/src/common"
	"bigdevops/src/config"
	"bigdevops/src/models"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/alertmanager/pkg/labels"
	"github.com/prometheus/alertmanager/types"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func AlertSilence(c *gin.Context) {

	// event 写入库的时候 把标签全部写入，silence
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.AlertWebhookConfig)
	fingerprint := c.DefaultQuery("fingerprint", "")
	byName := c.DefaultQuery("by_name", "")
	byNameBool := false
	if byName == "1" {
		byNameBool = true
	}
	hour := c.DefaultQuery("hour", "")

	hourInt, _ := strconv.Atoi(hour)
	// 通过 Fingerprint 去查询到event ，再拼接标签
	event, err := models.GetMonitorAlertEventByFingerprintId(fingerprint)
	if err != nil {
		c.String(500, fmt.Sprintf("通过 Fingerprint 去查询到event错误:%v", err.Error()))
		return
	}

	matchers := labels.Matchers{}
	event.GenMapFromKvs()
	for k, v := range event.LabelsM {
		m := &labels.Matcher{
			Type:  labels.MatchEqual,
			Name:  k,
			Value: v,
		}
		matchers = append(matchers, m)
	}
	if byNameBool {
		matchers = labels.Matchers{
			{
				Type:  labels.MatchEqual,
				Name:  common.MONITOR_ALERT_NAME_KEY,
				Value: event.LabelsM[common.MONITOR_ALERT_NAME_KEY],
			},
		}
	}

	si := types.Silence{
		ID:        "",
		Matchers:  matchers,
		StartsAt:  time.Now(),
		EndsAt:    time.Now().Add(time.Duration(hourInt) * time.Hour),
		CreatedBy: "xiaoyi",
		Comment:   "小乙创建的告警静默",
		Status:    types.SilenceStatus{},
	}

	jsonStr, _ := json.Marshal(si)
	url := fmt.Sprintf("%s/%s", sc.AlertManagerApi, "api/v1/silences")
	emptyMap := map[string]string{}
	bodyBytes, err := common.PostWithJsonString(
		sc.Logger, "AlertSilence",
		sc.HttpRequestGlobalTimeoutSeconds,
		url,
		string(jsonStr),
		emptyMap,
		emptyMap,
	)

	if err != nil {
		sc.Logger.Error("告警静默调用alertmanager接口失败",
			zap.Error(err),
			zap.Any("fingerprint", fingerprint),
			zap.Any("out", string(bodyBytes)),
		)
		c.String(400, fmt.Sprintf("告警静默调用alertmanager接口失败:%v", err.Error()))
		return
	}

	// 解析 屏蔽结果
	var sr *common.AlertmanagerSilenceResponse
	json.Unmarshal(bodyBytes, &sr)
	if sr != nil {
		event.SilenceId = sr.Data.SilenceId
		event.UpdateOne()
	}

	c.String(200, string(bodyBytes))

}

func AlertUnSilence(c *gin.Context) {

	// event 写入库的时候 把标签全部写入，silence
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.AlertWebhookConfig)
	fingerprint := c.DefaultQuery("fingerprint", "")
	event, err := models.GetMonitorAlertEventByFingerprintId(fingerprint)
	if err != nil {
		c.String(500, fmt.Sprintf("通过 Fingerprint 去查询到event错误:%v", err.Error()))
		return
	}

	url := fmt.Sprintf("%s/%s/%v", sc.AlertManagerApi, "api/v1/silence", event.SilenceId)
	emptyMap := map[string]string{}
	bodyBytes, err := common.DeleteWithId(
		sc.Logger, "AlertSilence",
		sc.HttpRequestGlobalTimeoutSeconds,
		url,
		emptyMap,
		emptyMap,
	)

	if err != nil {
		sc.Logger.Error("取消告警静默调用alertmanager接口失败",
			zap.Error(err),
			zap.Any("fingerprint", fingerprint),
			zap.Any("out", string(bodyBytes)),
		)
		c.String(400, fmt.Sprintf("取消告警静默调用alertmanager接口失败:%v", err.Error()))
		return
	}

	c.String(200, string(bodyBytes))

}
